package comWorld.favorite;

import com.gjs.tools.JDBC.JDBCTools;
import comWorld.blog.BlogInfo;
import comWorld.blog.BlogInfos;
import comWorld.user.UserStatus;

public class FavoriteManage {
	public static BlogInfos getBlogFavorites(int userId) {
		String sql = "SELECT bi.user_id userId, bi.blog_id blogId, bi.title title FROM "
				+ "blog_info bi, blog_collect bco WHERE bi.blog_id = bco.blog_id AND bco.user_id = ?";
		BlogInfos blogInfos = new BlogInfos(userId, JDBCTools.getObjects(BlogInfo.class, sql, userId));
		return blogInfos;
	}
	
	public static boolean addBlogFavor(int blogId, int userId) {
		String sql = "UPDATE blog_info SET collect_count = collect_count + 1 WHERE blog_id = ?";
		JDBCTools.update(sql, blogId);
		String sql2 = "INSERT INTO blog_collect VALUES(?,?)";
		return JDBCTools.insert(sql2, userId, blogId) > 0;
	}
	
	public static boolean deleteBlogFavor(int blogId, int userId) {
		String sql = "UPDATE blog_info SET collect_count = collect_count - 1 WHERE blog_id = ?";
		JDBCTools.update(sql, blogId);
		String sql2 = "DELETE FROM blog_collect WHERE user_id = ? AND blog_id = ?";
		return JDBCTools.update(sql2, userId, blogId) > 0;
	}
	
	public static boolean judgeBlogHasCollected(UserStatus visitorStatus, int blogId) {
		boolean collected = false;
		
		if (visitorStatus.isLogin()) {
			String sql = "SELECT user_id FROM blog_collect WHERE user_id = ? AND blog_id = ?";
			collected = JDBCTools.queryHasData(sql, visitorStatus.getId(), blogId) > 0 ? true : false;
		}
		return collected;
	}
}
